package org.jash.sportnews2109.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import dagger.hilt.android.AndroidEntryPoint
import org.jash.common.adapter.CommonAdapter
import org.jash.common.mvvm.BaseActivity
import org.jash.sportnews2109.BR
import org.jash.sportnews2109.R
import org.jash.sportnews2109.databinding.ActivitySearchBinding
import org.jash.sportnews2109.entity.News
import org.jash.sportnews2109.vm.SearchViewModel

@AndroidEntryPoint
@Route(path = "/news/search")
class SearchActivity : BaseActivity<ActivitySearchBinding, SearchViewModel>() {
    val adapter by lazy { CommonAdapter<News>(R.layout.news_item, BR.news) }
    @Autowired
    @JvmField
    var key:String = ""
    override fun initView() {
        binding.recycler.adapter = adapter
        binding.search.editText.setOnEditorActionListener { v, _, event ->
            when(event.action) {
                KeyEvent.ACTION_DOWN -> {
                    key = v.text.toString()
                    binding.searchBar.text = key
                    viewModel.search(key)
                    binding.search.hide()
                }
            }
            true
        }
        setSupportActionBar(binding.searchBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(com.google.android.material.R.drawable.abc_ic_ab_back_material)
    }

    override fun initData() {
        ARouter.getInstance().inject(this)
        viewModel.newsLiveData.observe(this, this::load)
        viewModel.search(key)
        binding.searchBar.text = key

    }
    fun load(list:List<News>) {
        list.forEach { it.key = key }
        adapter.clear()
        adapter += list
    }
}